package com.test.wehelpu.fragment;

///////轮播包
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/////////
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import android.widget.Toast;
import com.test.wehelpu.R;
import com.test.wehelpu.activity.*;
import com.test.wehelpu.adapter.ClassHelpMainAdapter;
import com.test.wehelpu.adapter.GridViewAdapter;
import com.test.wehelpu.model.ClassHelp;
import com.test.wehelpu.utils.Constant;

import cn.bmob.v3.Bmob;
import com.test.wehelpu.view.ShowPicGridView;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class TeachFragment extends Fragment implements View.OnClickListener{
    //////轮播变量
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;
    private int currentItem;
    //记录上一次点的位置
    private int oldPosition = 0;
    //存放图片的id
    private int[] imageIds = new int[]{
            R.drawable.img1,
            R.drawable.img2,
            R.drawable.img3,
            R.drawable.img4,
            R.drawable.img2,
    };
    //存放图片的标题
    private String[] titles = new String[]{
            "微帮友",
            "广告位招租",
            "广告位招租",
            "给予",
            "广告位招租"
    };
    private TextView title;
    private ViewPagerAdapter ViewPageradapter;
    private ScheduledExecutorService scheduledExecutorService;

    //////////轮播变量结束
    private ViewGroup group;
    private RecyclerView rv_help;
    private List<ClassHelp> list_help = new ArrayList<>();
    private ClassHelpMainAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean isRefreshing = false;
    private List<String> favorList;
    private ClassHelp classHelp;
    private ShowPicGridView gridView;
    private GridViewAdapter gridViewAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        group = (ViewGroup) inflater.inflate(R.layout.fragment_teach,container,false);
        Bmob.initialize(getContext(), Constant.BMOB_APPKEY);
        initView();
        refreshData();
        setView();
        return group;

    }
    private void setView(){
        mViewPaper = (ViewPager)group.findViewById(R.id.vp);

        //显示的图片
        images = new ArrayList<ImageView>();
        for(int i = 0; i < imageIds.length; i++){
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的小点
        dots = new ArrayList<View>();
        dots.add(group.findViewById(R.id.dot_0));
        dots.add(group.findViewById(R.id.dot_1));
        dots.add(group.findViewById(R.id.dot_2));
        dots.add(group.findViewById(R.id.dot_3));
        dots.add(group.findViewById(R.id.dot_4));

        title = (TextView) group.findViewById(R.id.title);
        title.setText(titles[0]);

        ViewPageradapter = new ViewPagerAdapter();
        mViewPaper.setAdapter(ViewPageradapter);
        mViewPaper.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(position).setBackgroundResource(R.drawable.point_w);
                dots.get(oldPosition).setBackgroundResource(R.drawable.point_b);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }
    /*定义的适配器*/
    public class ViewPagerAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            // TODO Auto-generated method stub
//          super.destroyItem(container, position, object);
//          view.removeView(view.getChildAt(position));
//          view.removeViewAt(position);
            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            view.addView(images.get(position));
            return images.get(position);
        }

    }
    /**
     * 利用线程池定时执行动画轮播
     */
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS);
    }

    /**
     * 图片轮播任务
     * @author liuyazhuang
     *
     */
    private class ViewPageTask implements Runnable{

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        };
    };
    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if(scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }




    @Override
    public void onResume() {
        super.onResume();
        refreshData();
    }

    private void initView() {
        rv_help = group.findViewById(R.id.rv_classhelp_main);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        rv_help.setLayoutManager(layoutManager);
        //测试item
        adapter = new ClassHelpMainAdapter(getContext(),list_help);
        rv_help.setAdapter(adapter);
        rv_help.setItemAnimator(new DefaultItemAnimator());
//        adapter.setOnItemClickListener(new ClassHelpMainAdapter.OnItemClickListener(){
//            @Override
//            public void onItemClick(View view, final int position) {
//                switch (view.getId()){
//                    //点击头像、用户名  -->进入用户信息详情
//                    case R.id.civ_help_head:
//                    case R.id.tv_help_nickname:
//                    case R.id.tv_help_department:
//
//                        Intent intent = new Intent(getContext(), FriendInfoActivity.class);
//                        intent.putExtra("nickname",list_help.get(position).getNickname());
//                        intent.putExtra("isFriend",false);
//                        Log.d("friendname", "onItemClick: "+list_help.get(position).getNickname());
//                        startActivity(intent);
//
//                        break;
//                    //点击内容、时间、评论 -->  进入帮助详情
//                    case R.id.tv_help_content:
//                    case R.id.tv_help_time:
////                    case R.id.ll_help_comment:
//                        Intent detailIntent = new Intent(getContext(), ClassHelpDetailActivity.class);
////                            detailIntent.putExtra("id",list_help.get(position).getId());
//                        //通过静态对象传值
//                        detailIntent.putExtra("title","帮助详情");
//                        detailIntent.putExtra("type","classhelp");
//                        Constant.curHelp = list_help.get(position);
//                        startActivity(detailIntent);
//                        break;
//                    case R.id.iv_ignore:
//                        //删除
//                        AlertDialog dialog = new AlertDialog.Builder(getContext()).setTitle("提示")
//                                .setMessage("确定忽略这条帮助吗？")
//                                .setPositiveButton("是的", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        adapter.deleteData(position);
//                                    }
//                                })
//                                .setNegativeButton("不",null)
//                                .show();
//                        break;
////                    case R.id.ll_help_favor:
//////                            Toast.makeText(getContext(),"点赞",Toast.LENGTH_SHORT).show();
//////                        addFavor(position);
////                        break;
////                    case R.id.ll_help_share:
//////                            Toast.makeText(getContext(),"转发一下",Toast.LENGTH_SHORT).show();
////                        Constant.share(getContext(),"转发到","来自「微帮友」的分享："+list_help.get(position).getContent());
////                        break;
////                    case R.id.gv_help_pic:
////                        classHelp = list_help.get(position);
////                        break;
//                }
//            }
//        });


        //下滑刷新
        swipeRefreshLayout = group.findViewById(R.id.swl_classhelp_main);
        swipeRefreshLayout.setColorSchemeColors(Color.GREEN,Color.BLUE,Color.RED);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isRefreshing) {
                    isRefreshing = true;
                    //刷新完更新数据   在handler中完成
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            swipeRefreshLayout.setRefreshing(false);
                            isRefreshing = false;
                            //执行刷新

                            refreshData();
                            Toast.makeText(getContext(),"刷新成功~",Toast.LENGTH_SHORT).show();
                        }
                    }, 2000);   //转圈圈2秒
                }
            }
        });
    }
    public void refreshData() {
        if (BmobUser.getCurrentUser() == null){
            list_help.clear();
            adapter.notifyDataSetChanged();
            Toast.makeText(getContext(),"请先登录",Toast.LENGTH_SHORT).show();
            return;
        }
        BmobQuery<ClassHelp> query = new BmobQuery<>();
        query.addWhereEqualTo("tag","help");
        query.setLimit(50);       //默认返回10条
        query.findObjects(new FindListener<ClassHelp>() {
            @Override
            public void done(List<ClassHelp> list, BmobException e) {
                if (e==null){
                    if (list.size() != 0){
                        list_help.clear();
                        adapter.notifyDataSetChanged();
                        for (ClassHelp help: list) {
                            adapter.addData(0,help);
                        }
                        adapter.notifyDataSetChanged();
                        Log.d("queryHelpItem", "找到"+list.size()+"条数据");
                    }
                }else {
                    Log.d("queryHelpItem", "error "+e.getMessage());
                }
            }
        });
//        rv_help.scrollToPosition(0);
    }

    @Override
    public void onClick(View v) {
        Intent publicIntent = new Intent(getContext(),ClassHelpPublishActivity.class);
    }

}
